<template>
  <div>
    <p class="title">总体效果</p>
    <div class="panel">
      <div class="panel-header">
        广告名称：<span>{{ statisticData.advertName }}</span>
        <div class="adsense-select">
          <p>广告位:</p>
          <el-select
            v-model="advertLocationEnumValue"
            placeholder="请选择"
            @change="changeEnumValue"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="data-statistics">
        <div class="total-statistics">
          <div class="show-statistics">
            <img src="@/assets/images/total-show.png" alt="" />
            <div>
              <p>广告总展示数</p>
              <p>{{ statisticData.browseTotal }}</p>
            </div>
          </div>
          <div class="show-statistics">
            <img src="@/assets/images/total-click.png" alt="" />
            <div>
              <p>广告总点击数</p>
              <p>{{ statisticData.clickTotal }}</p>
            </div>
          </div>
          <div class="show-statistics">
            <img src="@/assets/images/total-click-rate.png" alt="" />
            <div>
              <p>广告总点击率</p>
              <p>{{ statisticData.rateTotal }}</p>
            </div>
          </div>
        </div>
        <div class="today-statistics">
          <div class="show-statistics">
            <img src="@/assets/images/today-show.png" alt="" />
            <div>
              <p>广告日均展示数</p>
              <p>{{ statisticData.dayBrowse }}</p>
            </div>
          </div>
          <div class="show-statistics">
            <img src="@/assets/images/today-click.png" alt="" />
            <div>
              <p>广告日均点击数</p>
              <p>{{ statisticData.dayClick }}</p>
            </div>
          </div>
          <div class="show-statistics">
            <img src="@/assets/images/today-click-rate.png" alt="" />
            <div>
              <p>广告日均点击率</p>
              <p>{{ statisticData.dayRate }}</p>
            </div>
          </div>
        </div>
      </div>
      <div v-loading="datacardLoading">
        <div class="charts-search">
          <p class="search-title">数据类型</p>
          <div class="btn-wrapper">
            <button
              :class="{ active: statisticDateType === 'day' }"
              @click="typeClick('day')"
            >
              按日</button
            ><button
              :class="{ active: statisticDateType === 'hour' }"
              @click="typeClick('hour')"
            >
              按小时
            </button>
          </div>
          <p class="search-title">数据时间</p>
          <p v-if="statisticDateType === 'hour'">
            <el-date-picker
              v-model="time"
              type="date"
              :picker-options="startTimePickerOptions"
              placeholder="请选择时间"
            >
            </el-date-picker>
          </p>
          <p v-if="statisticDateType === 'day'">
            <SearchDatePicker
              :start.sync="startTime"
              :end.sync="endTime"
              :disable-date="{
                range: 24 * 3600 * 30 * 1000,
                banTomorrow: true,
              }"
            />
          </p>
          <el-button
            v-if="
              resourceSet.includes(
                '/web/activity-management/advert-management/advertStatistic-management/查询'
              )
            "
            icon="el-icon-search"
            type="success"
            @click="getAdvertHeader"
            class="search-btn"
            >查询</el-button
          >
        </div>
        <div id="main" class="charts"></div>
      </div>
    </div>

    <p class="title">效果详情</p>
    <TableSearch
      v-loading="loading"
      ref="tableSearch"
      :pageNameDisplay="false"
      :search-path="searchPath"
      :formItemsInline="formItemsInline"
      :form="form"
      :columns="columns"
      :tableData="tableData"
      :resetBtnDisplay="false"
      @handleTableData="handleTableData"
    >
      <template slot="advertLocationEnum">
        <el-form-item label="广告位:" label-width="80px">
          <el-select
            v-model="form.advertLocationEnum"
            placeholder="请选择广告位"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in options"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </template>
    </TableSearch>
  </div>
</template>
<script>
import { typeMap } from '@/utils/format'
import { getStatisticAdvertHeader, getAdvertLogList } from '@/api/activity'
import TableSearch from '@/components/TableSearch'
import SearchDatePicker from '@/components/SearchDatePicker'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import Big from 'big.js'

export default {
  name: 'advertStatistics',
  components: { TableSearch, SearchDatePicker },
  data() {
    return {
      options: [
        {
          value: 'ALL',
          label: '全部广告位',
        },
        {
          value: 'HOMEPAGE',
          label: '小程序首页',
        },
        {
          value: 'CHARGEPAGE',
          label: '充电确认页',
        },
      ],
      advertLocationEnumValue: 'ALL',
      loading: false,
      datacardLoading: false,
      startTimePickerOptions: {},
      searchPath:
        '/web/activity-management/advert-management/advertStatistic-management/查询',
      statisticDateType: 'day',
      time: dayjs().subtract(1, 'day'),
      startTime: dayjs().subtract(15, 'day').startOf('day').valueOf(),
      endTime: dayjs().subtract(1, 'day').endOf('day').valueOf(),
      columns: [
        {
          label: '用户手机号',
          prop: 'mobile',
          resourceId:
            '/web/activity-management/advert-management/advertStatistic-management/用户手机号',
        },
        {
          label: '查看/点击时间',
          prop: 'readTime',
          formatter: (row) => {
            return typeMap.formatTime(row.readTime)
          },
          resourceId:
            '/web/activity-management/advert-management/advertStatistic-management/时间',
        },
        {
          label: '用户查看类型',
          prop: 'readType',
          formatter: (row) => {
            return row.readType === 1 ? '展示查看' : '点击查看'
          },
          resourceId:
            '/web/activity-management/advert-management/advertStatistic-management/查看类型',
        },
      ],
      tableData: {},
      formItemsInline: [
        {
          slot: 'advertLocationEnum',
        },
        {
          type: 'radio',
          value: 'advertReadTypeEnum',
          options: [
            {
              label: 'ALL',
              text: '全部',
            },
            {
              label: 'BROWSE',
              text: '按展示查看',
            },
            {
              label: 'CLICK',
              text: '按点击查看',
            },
          ],
        },
      ],
      form: {
        advertReadTypeEnum: 'ALL',
        advertLocationEnum: 'ALL',
      },
      myChart: null,
      statisticData: {
        browseTotal: 0,
        clickTotal: 0,
        rateTotal: 0,
        dayBrowse: 0,
        dayClick: 0,
        dayRate: 0,
      },
    }
  },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
  },
  mounted() {
    let disabledFunc = (time) => {
      return time.getTime() > Date.now() - 24 * 3600 * 1000
    }

    this.$set(this.startTimePickerOptions, 'disabledDate', disabledFunc)

    this.myChart = echarts.init(document.getElementById('main'))
    const colors = ['#1A6DEB', '#FAAD14', '#54BB5B']
    let option = {
      color: colors,
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: (params) => {
          let result = params[0].name + '<br/>'
          params.forEach((item) => {
            let { marker, data, seriesName } = item
            if (item.seriesName === '点击率') {
              //百分比数据
              data = new Big(data).times(100) + '%'
            }
            result =
              result +
              `${marker}${seriesName}:<span style="margin-left:20px;font-weight: 700;display: inline-block;">${data}</span>` +
              '<br/>'
          })
          return result
        },
      },
      grid: {
        // show:true,
        containLabel: true,
        top: '50',
        bottom: '20',
        left: '10',
        right: '10',
      },
      legend: {
        data: ['点击数', '展示数', '点击率'],
        right: 10,
        top: 0,
      },
      xAxis: [
        {
          type: 'category',
          // axisTick: {
          //   alignWithLabel: true
          // },
          axisTick: {
            show: false,
          },
          data: [],
        },
      ],
      yAxis: [
        {
          type: 'value',
          // name: '次数',
          position: 'left',
          alignTicks: true,
          axisLabel: {
            formatter: '{value} ',
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: ['#DDDDDD'],
            },
          },
        },
        {
          type: 'value',
          // name: '频率',
          position: 'right',
          alignTicks: true,
          axisLabel: {
            // formatter: '{value}',
            formatter: function (value) {
              return value * 100 + '%'
            },
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: ['#DDDDDD'],
            },
          },
          axisPointer: {
            label: {
              formatter: (params) => {
                return new Big(params.value).round(4).times(100) + '%'
              },
            },
          },
        },
      ],
      series: [
        {
          name: '点击数',
          type: 'bar',
          data: [],
          barWidth: '15%',
          barMaxWidth: '16',
        },
        {
          name: '展示数',
          type: 'bar',
          data: [],
          barWidth: '15%',
          barMaxWidth: '16',
        },
        {
          name: '点击率',
          type: 'line',
          yAxisIndex: 1,
          smooth: true,
          data: [],
        },
      ],
    }
    this.myChart.setOption(option)
    window.addEventListener('resize', this.myChart.resize)
    this.getAdvertHeader()
  },
  methods: {
    buildDiagram() {},
    getAdvertHeader() {
      let advertId = this.$route.params.advertId
      let params = {
        advertId: advertId,
        statisticDateType: this.statisticDateType === 'day' ? 1 : 2,
        startTime:
          this.statisticDateType === 'day'
            ? this.startTime
            : dayjs(this.time).startOf('day').valueOf(),
        endTime:
          this.statisticDateType === 'day'
            ? this.endTime
            : dayjs(this.time).endOf('day').valueOf(),
      }
      if (this.advertLocationEnumValue !== 'ALL') {
        params.advertLocationEnum = this.advertLocationEnumValue
      }
      this.datacardLoading = true
      getStatisticAdvertHeader(params).then(
        (res) => {
          this.datacardLoading = false
          this.statisticData = {
            browseTotal: res.browseTotal,
            clickTotal: res.clickTotal,
            rateTotal: new Big(res.rateTotal).times(100) + '%',
            dayBrowse: res.dayBrowse,
            dayClick: res.dayClick,
            dayRate: new Big(res.dayRate).times(100) + '%',
            advertName: res.advertName,
          }
          let statisticTime = []
          let browseTotal = []
          let clickTotal = []
          let rateTotal = []

          res.detailVos.forEach((item) => {
            statisticTime.push(
              typeMap.formatTime(
                item.statisticTime,
                this.statisticDateType === 'day' ? 'YYYY-MM-DD' : 'HH:ss'
              )
            )
            browseTotal.push(item.browseTotal)
            clickTotal.push(item.clickTotal)
            rateTotal.push(item.rateTotal)
          })
          this.myChart.setOption({
            xAxis: [
              {
                type: 'category',
                data: statisticTime,
              },
            ],
            series: [
              {
                name: '点击数',
                data: clickTotal,
              },
              {
                name: '展示数',
                data: browseTotal,
              },
              {
                name: '点击率',
                data: rateTotal,
              },
            ],
          })
        },
        () => {
          this.datacardLoading = false
        }
      )
    },
    changeEnumValue() {
      this.getAdvertHeader()
    },
    handleTableData(params) {
      this.loading = true
      params = {
        advertId: this.$route.params.advertId,
        ...params,
      }

      if (params.advertReadTypeEnum === 'ALL') delete params.advertReadTypeEnum
      if (params.advertLocationEnum === 'ALL') delete params.advertLocationEnum
      getAdvertLogList(params).then(
        (res) => {
          this.loading = false
          this.tableData = {
            list: res.list,
            totalCount: res.totalAmount,
          }
        },
        () => {
          this.loading = false
        }
      )
    },
    typeClick(val) {
      this.statisticDateType = val
      this.getAdvertHeader()
    },
  },
}
</script>
<style lang="scss" scoped>
.title {
  font-weight: bold;
  color: #333333;
  font-size: 18px;
  padding-left: 24px;
}
.panel {
  padding-left: 30px;
  padding-right: 30px;
  .panel-header {
    font-weight: bold;
    color: #333333;
    font-size: 14px;
    &::before {
      margin-left: 0;
    }
    &::after {
      height: 0;
    }
    span {
      color: #1a6deb;
    }
    .adsense-select {
      display: flex;
      margin-top: 10px;
      align-items: center;
      margin-right: 10px;
    }
  }
  .data-statistics {
    width: 100%;
    display: flex;
    margin-top: 50px;
    margin-bottom: 30px;
    .total-statistics,
    .today-statistics {
      width: 49%;
      display: flex;
      justify-content: space-around;
      .show-statistics {
        display: flex;
        align-items: center;
        img {
          width: 50px;
          margin-right: 10px;
        }
        div {
          p:nth-child(1) {
            font-size: 14px;
            color: #5a5a5a;
            margin: 0;
          }
          p:nth-child(2) {
            font-size: 20px;
            color: #333333;
            margin: 0;
            font-weight: bold;
          }
        }
      }
    }
  }

  .charts-search {
    width: 100%;
    display: flex;
    align-items: center;
    .search-title {
      font-size: 14px;
      color: #333333;
      margin-right: 10px;
    }
    .btn-wrapper {
      margin-right: 20px;
      button:focus {
        outline: none;
      }
      button {
        cursor: pointer;
        width: 100px;
        height: 36px;
        font-size: 14px;
        background: #ffffff;
        color: #333333;
        border: 1px solid #d9d9d9;
      }
      button:nth-child(1) {
        border-radius: 4px 0px 0px 4px;
      }
      button:nth-child(2) {
        border-radius: 0px 4px 4px 0px;
      }

      button.active {
        background: rgba(26, 109, 235, 0.05);
        border: 1px solid #1a6deb;
        color: #1875f0;
      }
    }
    .search-btn {
      margin-left: 20px;
    }
  }

  .charts {
    width: 100%;
    height: 400px;
  }
}

::v-deep {
  .table-dash {
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
  }
  .form-wrapper {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    .iform {
      width: 50%;
      flex: none !important;
    }
    .form-content {
      justify-content: flex-start !important;
    }
  }
}
</style>
